import axios from "axios"; // 引入axios
import { Message } from "element-ui";
import { getUserToken } from "@/utils/storage";
import $router from "@/router";
let { NODE_ENV } = process.env;
//连接mock连接
const http = axios.create({
  // baseURL: "/api",
  timeout: 3 * 60 * 1000, //3分钟
  responseType: "json",
  // withCredentials: true,
  headers: {
    httponly: true,
    secure: true,
  },
});
function removeLoading() {
  let loadingDom = document.querySelector(".el-loading-mask.loading");
  loadingDom && loadingDom.remove();
  //按钮下的loading
  let loadingBtn = document.querySelectorAll(".el-button.is-loading");
  loadingBtn?.forEach((item) => {
    item.classList.remove("is-loading"); //移除class样式
    item.removeAttribute("disabled"); //移除按钮禁用
    let loadingDom = item.children[0];
    if (loadingDom.className == "el-icon-loading") {
      loadingDom.remove();
    }
  });
}
/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function get(url, params) {
  return new Promise((resolve, reject) => {
    http
      .get(url, { params: { ...params } })
      .then((res) => {
        resolve(res.data);
      })
      .catch((err) => {
        removeLoading();
        reject(err.data);
      });
  });
}
/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 * @param {Boolean} ifToken [请求时是否携带token/formdata类型的数据需要自定义数据类型]
 */
export function post(url, params, ifToken = true) {
  return new Promise((resolve, reject) => {
    if (ifToken) {
      params = {
        ...params,
      };
    }
    http
      .post(url, params)
      .then((res) => {
        resolve(res.data);
      })
      .catch((err) => {
        removeLoading();
        reject(err.data);
      });
  });
}
/**
 * postFile方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function postFile(url, params) {
  return new Promise((resolve, reject) => {
    http
      .post(url, params)
      .then((res) => {
        resolve(res.data);
      })
      .catch((err) => {
        removeLoading();
        reject(err.data);
      });
  });
}
/**
 * put方法，对应put请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function put(url, params) {
  return new Promise((resolve, reject) => {
    http
      .put(url, { ...params, userToken: getUserToken() })
      .then((res) => {
        resolve(res.data);
      })
      .catch((err) => {
        removeLoading();
        reject(err.data);
      });
  });
}
/**
 * del方法，对应delete请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function del(url, params) {
  return new Promise((resolve, reject) => {
    http
      .delete(url, { params: { ...params, userToken: getUserToken() } })
      .then((res) => {
        resolve(res.data);
      })
      .catch((err) => {
        removeLoading();
        reject(err.data);
      });
  });
}

/**
 * @函数功能:请求拦截器 添加请求头
 * @参数输入:
 * @函数返回:
 */
http.interceptors.request.use(
  (config) => {
    // 从存储中获取 token
    const token = getUserToken();
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (err) => {
    console.log(err);
    return Promise.reject(err);
  },
);

/**
 * @函数功能:拦截器
 * @参数输入:
 * @函数返回:
 */
http.interceptors.response.use(
  (data) => {
    //响应出现问题
    if (data.data.code !== 200) {
      if (data.data.code !== 0) {
        data.data.code !== 200 && Message.warning({ message: data.data.msg });
        return Promise.reject(err);
      }
    }
    return data;
  },
  (err) => {
    // //无效的token
    if (err.response.status === 401) {
      $router.push("/login");
      return;
    }
    // debugger;
    Message.error({
      message: `程序出错了，请联系管理员：${err.response.statusText}（${err.response.status}）`,
    });
    return Promise.reject(err);
  },
);
